package com.zzyk.main.controller;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.configuration.jwt.JwtUtil;
import com.zzyk.main.model.pojo.PageView;
import com.zzyk.main.model.pojo.SysRole;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.service.ISysUserService;
import com.zzyk.main.utils.SpringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseController {

    @Autowired
    private ISysUserService userService;

    protected SysUser currentUser() throws UserException {
        String token = SpringUtils.getHeader("token");
        if (ObjectUtil.isNull(token)) {
            throw new UserException("非法token");
        }
        String username = JwtUtil.getUsername(token);
        if (ObjectUtil.isNull(username)) {
            throw new UserException("请登录后操作");
        }
        SysUser userDetails = userService.getUserDetails(username);
        if (ObjectUtil.isNull(userDetails)) {
            throw new UserException("获取用户信息异常");
        }
        return userDetails;
    }
    protected SysUser currentUserByToken(String token) throws UserException {
        String username = JwtUtil.getUsername(token);
        if (ObjectUtil.isNull(username)) {
            throw new UserException("请登录后操作");
        }
        SysUser userDetails = userService.getUserDetails(username);
        if (ObjectUtil.isNull(userDetails)) {
            throw new UserException("获取用户信息异常");
        }
        return userDetails;
    }
    protected void logout() {
        SecurityUtils.getSubject().logout();
    }

    protected boolean hasRole(int roleId) throws UserException {
        for (SysRole role : currentUser().getRoleSet()) {
            if (role.getId() == roleId) {
                return true;
            }
        }
        return false;
    }

    protected void setPage() {
        PageView pageView = PageView.getPageView();
        Integer pageIndex = pageView.getPageIndex();
        Integer pageSize = pageView.getPageSize();
        if (pageIndex != null && pageSize != null) {
            String orderBy = pageView.getOrderBy();
            PageHelper.startPage(pageIndex, pageSize, orderBy);
        }
    }
}
